'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { useToast } from '@/components/ui/ToastProvider';
import LoadingSpinner from '@/components/ui/LoadingSpinner';
import { CheckCircle, XCircle, Mail, ArrowRight, RefreshCw } from 'lucide-react';

export default function VerifyEmailPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { showSuccess, showError } = useToast();
  
  const [loading, setLoading] = useState(true);
  const [verificationStatus, setVerificationStatus] = useState<'loading' | 'success' | 'error' | 'resend'>('loading');
  const [resendLoading, setResendLoading] = useState(false);
  const [email, setEmail] = useState('');

  // 从URL参数获取验证令牌
  const token = searchParams.get('token');
  const emailParam = searchParams.get('email');

  useEffect(() => {
    if (emailParam) {
      setEmail(emailParam);
    }
    
    if (token) {
      verifyEmail(token);
    } else {
      setVerificationStatus('resend');
      setLoading(false);
    }
  }, [token, emailParam]);

  const verifyEmail = async (verificationToken: string) => {
    try {
      // 这里集成Better Auth的邮箱验证功能
      // 暂时模拟API调用
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 模拟验证结果（随机成功或失败用于演示）
      const success = Math.random() > 0.3;
      
      if (success) {
        setVerificationStatus('success');
        showSuccess('验证成功', '您的邮箱已成功验证');
      } else {
        setVerificationStatus('error');
        showError('验证失败', '验证链接无效或已过期');
      }
    } catch (error: any) {
      console.error('邮箱验证失败:', error);
      setVerificationStatus('error');
      showError('验证失败', error.message || '网络错误，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleResendVerification = async () => {
    if (!email) {
      showError('发送失败', '请输入邮箱地址');
      return;
    }

    setResendLoading(true);
    try {
      // 这里集成Better Auth的重发验证邮件功能
      // 暂时模拟API调用
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      showSuccess('邮件已发送', '验证邮件已重新发送到您的邮箱');
    } catch (error: any) {
      console.error('重发验证邮件失败:', error);
      showError('发送失败', error.message || '网络错误，请重试');
    } finally {
      setResendLoading(false);
    }
  };

  // 加载状态
  if (loading) {
    return (
      <div className="w-full text-center">
        <div className="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-6">
          <LoadingSpinner size="lg" text="" />
        </div>
        <h2 className="text-3xl font-bold text-gray-900 mb-4">
          验证中...
        </h2>
        <p className="text-gray-600">
          正在验证您的邮箱地址，请稍候
        </p>
      </div>
    );
  }

  // 验证成功
  if (verificationStatus === 'success') {
    return (
      <div className="w-full text-center">
        <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
          <CheckCircle className="h-10 w-10 text-green-600" />
        </div>
        <h2 className="text-3xl font-bold text-gray-900 mb-4">
          验证成功！
        </h2>
        <p className="text-gray-600 mb-8 text-lg">
          您的邮箱已成功验证，现在可以使用所有功能了
        </p>
        <button
          onClick={() => router.push('/auth/login')}
          className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors flex items-center justify-center space-x-2"
        >
          <span>前往登录</span>
          <ArrowRight className="h-4 w-4" />
        </button>
      </div>
    );
  }

  // 验证失败
  if (verificationStatus === 'error') {
    return (
      <div className="w-full text-center">
        <div className="w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6">
          <XCircle className="h-10 w-10 text-red-600" />
        </div>
        <h2 className="text-3xl font-bold text-gray-900 mb-4">
          验证失败
        </h2>
        <p className="text-gray-600 mb-8 text-lg">
          验证链接无效或已过期，请重新发送验证邮件
        </p>
        
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              邮箱地址
            </label>
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Mail className="h-5 w-5 text-gray-400" />
              </div>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                placeholder="输入您的邮箱地址"
                required
              />
            </div>
          </div>

          <button
            onClick={handleResendVerification}
            disabled={resendLoading}
            className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center space-x-2"
          >
            {resendLoading ? (
              <LoadingSpinner size="sm" text="" />
            ) : (
              <>
                <RefreshCw className="h-4 w-4" />
                <span>重新发送验证邮件</span>
              </>
            )}
          </button>

          <Link
            href="/auth/login"
            className="w-full bg-gray-100 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors flex items-center justify-center space-x-2"
          >
            <span>返回登录</span>
          </Link>
        </div>
      </div>
    );
  }

  // 重发验证邮件页面
  return (
    <div className="w-full text-center">
      <div className="w-20 h-20 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-6">
        <Mail className="h-10 w-10 text-yellow-600" />
      </div>
      <h2 className="text-3xl font-bold text-gray-900 mb-4">
        验证您的邮箱
      </h2>
      <p className="text-gray-600 mb-8 text-lg">
        请输入您的邮箱地址，我们将发送验证链接
      </p>

      <div className="space-y-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            邮箱地址
          </label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <Mail className="h-5 w-5 text-gray-400" />
            </div>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              placeholder="输入您的邮箱地址"
              required
            />
          </div>
        </div>

        <button
          onClick={handleResendVerification}
          disabled={resendLoading}
          className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center space-x-2"
        >
          {resendLoading ? (
            <LoadingSpinner size="sm" text="" />
          ) : (
            <>
              <span>发送验证邮件</span>
              <ArrowRight className="h-4 w-4" />
            </>
          )}
        </button>

        {/* 提示信息 */}
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-left">
          <h3 className="font-medium text-blue-900 mb-2">温馨提示：</h3>
          <ul className="text-blue-800 text-sm space-y-1">
            <li>• 验证链接将在24小时后过期</li>
            <li>• 请检查您的垃圾邮件文件夹</li>
            <li>• 验证后即可使用所有功能</li>
          </ul>
        </div>

        <Link
          href="/auth/login"
          className="text-blue-600 hover:text-blue-500 font-medium"
        >
          返回登录
        </Link>
      </div>
    </div>
  );
} 